package com.iamteer.dao.impl;

import java.util.List;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import com.iamteer.dao.IDishDao;
import com.iamteer.entity.Dish;
import com.iamteer.utils.JdbcUtils;

/**
 * 2. 菜品 dao 实现
 * @author Chuck
 *
 */
public class DishDao implements IDishDao {

	private QueryRunner qr = JdbcUtils.getQueryRunner();
	
	@Override
	public void add(Dish dish) {
		try {
			String sql = "insert into dish(dName,category_id,price,mprice,remark,img) values(?,?,?,?,?,?)";
			qr.update(sql,dish.getdName(), dish.getCategory_id(),
					dish.getPrice(), dish.getMprice(),dish.getRemark(),dish.getImg());
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	@Override
	public void delete(int id) {
		try {
			String sql = "delete from dish where id=?";
			qr.update(sql,id);
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	@Override
	public void update(Dish dish) {
		try {
			String sql = "update dish set dName=?,category_id=?,price=?,mprice=?,remark=?,img=? where id=?";
			qr.update(sql,dish.getdName(), dish.getCategory_id(),
					dish.getPrice(), dish.getMprice(),dish.getRemark(),dish.getImg(), dish.getId());
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	@Override
	public List<Dish> query() {
		try {
			String sql = "select * from dish";
			return qr.query(sql,new BeanListHandler<Dish>(Dish.class));
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	@Override
	public List<Dish> query(int category_id) {
		try {
			String sql = "select * from dish where category_id=?";
			return qr.query(sql,new BeanListHandler<Dish>(Dish.class), category_id);
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	@Override
	public List<Dish> query(String keyword) {
		try {
			String sql = "select * from dish where dName like ?";
			keyword = "%" + keyword + "%";
			return qr.query(sql,new BeanListHandler<Dish>(Dish.class), keyword);
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	@Override
	public Dish findById(int id) {
		try {
			String sql = "select * from dish where id=?";
			return qr.query(sql,new BeanHandler<Dish>(Dish.class), id);
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

}
